#!/bin/sh
#
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Set activate date in VPD. This script should be called during OOBE to write
# down the activate date.
#
# Since OOBE can be invoked multiple times, this script should check if the
# activate date has been written. If yes, do nothing.
#
# Example:
#   activate_date          set the activate date to now if not set yet
#   activate_date --clean  delete the activate date VPD key, if present.
#

# VPD program location
VPD="/usr/sbin/vpd"

# The field name of activate date in VPD
FIELD_NAME="ActivateDate"

# Partition to store activate date
PARTITION="RW_VPD"


die() {
  echo "$*" >&2
  exit 1
}


write_activate_date() {
  ${VPD} -i "${PARTITION}" -s "${FIELD_NAME}=$1" || die "vpd returns ERROR."
}

clean_activate_date() {
  echo "Clean Activate Date."
  ${VPD} -i "${PARTITION}" -d "${FIELD_NAME}" ||
    echo "Can't delete ${FIELD_NAME}, it may not exist in ${PARTITION}."
}

main() {
  if [ "$1" = "--clean" ]; then
    CLEAN=1
  else
    CLEAN=0
  fi

  # Get the current value in VPD. The output format is followed:
  #
  #   "ActivateDate"="2011-33"
  #
  # Consisting of year-week, this lower granularity is used to minimize
  # unique identity correlation by activation date.
  ACTIVATE_DATE="$("${VPD}" -i "${PARTITION}" -g "${FIELD_NAME}" || true)"

  # Always attempt to delete the key if requested.
  if [ ${CLEAN} -eq 1 ]; then
    clean_activate_date
  # If 1. no VPD entry is set, or
  #    2. ActivateDate is empty string,
  # Then, write down current time into VPD.
  else
    if [ -z "${ACTIVATE_DATE}" ]; then
      # No activate date is set. Use current UTC time.
      nowDate=$(date --utc "+%Y-%W")
      echo "Setting Activate Date to ${nowDate}."
      write_activate_date "${nowDate}"
    else
      # An activate date is set. Do nothing.
      echo "Activate Date has already been set to ${ACTIVATE_DATE}."
    fi
  fi
  echo "Done."
}

main $1
